<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 简单手写基础样式，替代外部 CSS -->
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: sans-serif;
        }

        body {
            background: #f5f7fa;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }

        .form-container {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            width: 320px;
        }

        .form-content h2 {
            text-align: center;
            margin-bottom: 1.5rem;
            font-size: 1.25rem;
            color: #333;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #666;
        }

        .form-group input {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .btn {
            width: 100%;
            padding: 0.6rem;
            background: #165dff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 0.5rem;
        }

        .btn:hover {
            background: #0e46c2;
        }

        .toggle-link {
            text-align: center;
            margin-top: 1rem;
            color: #165dff;
            cursor: pointer;
        }

        .toggle-link:hover {
            text-decoration: underline;
        }

        .error-message {
            color: red;
            font-size: 0.875rem;
            margin-top: 0.25rem;
            display: none;
        }

        .loading {
            display: none;
            margin-left: 0.5rem;
        }

        #registerForm {
            display: none;
        }
    </style>
    <title>登录注册</title>
</head>

<body>
<div class="form-container">
    <!-- 登录表单 -->
    <div id="loginForm" class="form-content">
        <h2>欢迎登录</h2>
        <form id="loginFormData">
            <div class="form-group">
                <label for="loginPhone">手机号</label>
                <input type="tel" id="loginPhone" placeholder="请输入手机号" pattern="[0-9]{11}">
                <div id="loginPhoneError" class="error-message">请输入正确的手机号</div>
            </div>
            <div class="form-group">
                <label for="loginPassword">密码</label>
                <input type="password" id="loginPassword" placeholder="请输入密码">
                <div id="loginPasswordError" class="error-message">请输入密码</div>
            </div>
            <button type="submit" id="loginBtn" class="btn">
                登录
                <span class="loading" id="loginSpinner">...</span>
            </button>
            <div class="toggle-link" id="toRegisterBtn">还没有账号？立即注册</div>
        </form>
    </div>

    <!-- 注册表单 -->
    <div id="registerForm" class="form-content">
        <h2>账号注册</h2>
        <form id="registerFormData">
            <div class="form-group">
                <label for="registerPhone">手机号</label>
                <input type="tel" id="registerPhone" placeholder="请输入手机号" pattern="[0-9]{11}">
                <div id="registerPhoneError" class="error-message">请输入正确的手机号</div>
            </div>
            <div class="form-group">
                <label for="registerPassword">密码</label>
                <input type="password" id="registerPassword" placeholder="设置6-16位密码（字母+数字）">
                <div id="registerPasswordError" class="error-message">密码需包含字母和数字，长度6-16位</div>
            </div>
            <div class="form-group">
                <label for="registerConfirmPassword">确认密码</label>
                <input type="password" id="registerConfirmPassword" placeholder="确认密码">
                <div id="registerConfirmPasswordError" class="error-message">两次输入的密码不一致</div>
            </div>
            <button type="submit" id="registerBtn" class="btn">
                注册
                <span class="loading" id="registerSpinner">...</span>
            </button>
            <div class="toggle-link" id="toLoginBtn">已有账号？立即登录</div>
        </form>
    </div>
</div>

<script>
    // DOM 元素获取
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    const toRegisterBtn = document.getElementById('toRegisterBtn');
    const toLoginBtn = document.getElementById('toLoginBtn');
    const loginFormData = document.getElementById('loginFormData');
    const registerFormData = document.getElementById('registerFormData');
    const loginBtn = document.getElementById('loginBtn');
    const registerBtn = document.getElementById('registerBtn');
    const loginSpinner = document.getElementById('loginSpinner');
    const registerSpinner = document.getElementById('registerSpinner');

    // 表单切换逻辑
    toRegisterBtn.addEventListener('click', () => {
        loginForm.style.display = 'none';
        registerForm.style.display = 'block';
    });
    toLoginBtn.addEventListener('click', () => {
        registerForm.style.display = 'none';
        loginForm.style.display = 'block';
    });

    // 手机号验证
    function validatePhone(phone, errorElement) {
        const phonePattern = /^1[3-9]\d{9}$/;
        if (!phonePattern.test(phone)) {
            errorElement.style.display = 'block';
            return false;
        } else {
            errorElement.style.display = 'none';
            return true;
        }
    }

    // 密码验证（字母 + 数字，6 - 16 位 ）
    function validatePassword(password, errorElement) {
        const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,16}$/;
        if (!passwordPattern.test(password)) {
            errorElement.style.display = 'block';
            return false;
        } else {
            errorElement.style.display = 'none';
            return true;
        }
    }

    // 确认密码验证
    function validateConfirmPassword(password, confirmPassword, errorElement) {
        if (password!== confirmPassword) {
            errorElement.style.display = 'block';
            return false;
        } else {
            errorElement.style.display = 'none';
            return true;
        }
    }

    // 登录表单提交
    loginFormData.addEventListener('submit', (e) => {
        e.preventDefault();
        const phone = document.getElementById('loginPhone').value.trim();
        const password = document.getElementById('loginPassword').value.trim();
        const phoneError = document.getElementById('loginPhoneError');
        const passwordError = document.getElementById('loginPasswordError');

        let isValid = true;
        if (!validatePhone(phone, phoneError)) isValid = false;
        if (!password) {
            passwordError.style.display = 'block';
            isValid = false;
        } else {
            passwordError.style.display = 'none';
        }

        if (!isValid) return;

        // 显示加载状态
        loginBtn.disabled = true;
        loginSpinner.style.display = 'inline-block';

        // 模拟请求（实际替换为你的后端接口 http://localhost:8080/login ）
        fetch('http://localhost:8080/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                phone: phone,
                password: password
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    // 假设后端返回 { code: 200, data: { token: "your_jwt_token" } }
                    const token = data.data.token;
                    localStorage.setItem('auth_token', token);
                    alert('登录成功，即将跳转');
                    setTimeout(() => {
                        window.location.href = 'http://localhost:8080/home.html';
                    }, 1500);
                } else {
                    alert('登录失败：' + data.message);
                }
            })
            .catch(error => {
                alert('登录出错：' + error.message);
                console.error('登录请求错误：', error);
            })
            .finally(() => {
                loginBtn.disabled = false;
                loginSpinner.style.display = 'none';
            });
    });

    // 注册表单提交
    registerFormData.addEventListener('submit', (e) => {
        e.preventDefault();
        const phone = document.getElementById('registerPhone').value.trim();
        const password = document.getElementById('registerPassword').value.trim();
        const confirmPassword = document.getElementById('registerConfirmPassword').value.trim();
        const phoneError = document.getElementById('registerPhoneError');
        const passwordError = document.getElementById('registerPasswordError');
        const confirmPasswordError = document.getElementById('registerConfirmPasswordError');

        let isValid = true;
        if (!validatePhone(phone, phoneError)) isValid = false;
        if (!validatePassword(password, passwordError)) isValid = false;
        if (!validateConfirmPassword(password, confirmPassword, confirmPasswordError)) isValid = false;

        if (!isValid) return;

        registerBtn.disabled = true;
        registerSpinner.style.display = 'inline-block';

        // 模拟请求（实际替换为你的后端接口 http://localhost:8080/enroll ）
        fetch('http://localhost:8080/enroll', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                phone: phone,
                password: password
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    alert('注册成功，请登录');
                    // 切换到登录表单
                    registerForm.style.display = 'none';
                    loginForm.style.display = 'block';
                    // 填充手机号
                    document.getElementById('loginPhone').value = phone;
                } else {
                    alert('注册失败：' + data.message);
                }
            })
            .catch(error => {
                alert('注册出错：' + error.message);
                console.error('注册请求错误：', error);
            })
            .finally(() => {
                registerBtn.disabled = false;
                registerSpinner.style.display = 'none';
            });
    });

    // 实时监听输入，触发验证
    document.getElementById('loginPhone').addEventListener('input', function () {
        validatePhone(this.value.trim(), document.getElementById('loginPhoneError'));
    });
    document.getElementById('registerPhone').addEventListener('input', function () {
        validatePhone(this.value.trim(), document.getElementById('registerPhoneError'));
    });
    document.getElementById('registerPassword').addEventListener('input', function () {
        validatePassword(this.value.trim(), document.getElementById('registerPasswordError'));
    });
    document.getElementById('registerConfirmPassword').addEventListener('input', function () {
        const pwd = document.getElementById('registerPassword').value.trim();
        validateConfirmPassword(pwd, this.value.trim(), document.getElementById('registerConfirmPasswordError'));
    });
</script>
</body>

</html>